import { getUserInfo,getTokenKey, setUserInfo, removeUserInfo } from "../../utils/auth"
import { showFiles, handleFileUploading, deleteFile } from "../../utils/file";
import { getLocationInfo} from "../../utils/location.js";
import { deleteMarker, deleteFileFromDbs,uploadInitFile } from "../../utils/user";

const app = getApp();
Page({
  data: {
    user:{},
    userType:'',
    username:'',
    nickname:'',
    belongs:{},
    phoneNumber:'',
    credits:'',
    isPopShow: false,
    province : '陕西省',
    city : '西安市',
    stations: [],
    imgData: {
      fileType: 'initial',
      size: 82999,
      tempFilePath:''
    },
  },

  onLoad(options){
    console.log(options)
    if(options.userType && options.avatarUrl){
      this.setData({
        userType: options.userType,
        'imgData.tempFilePath': decodeURIComponent(options.avatarUrl) 
      })
    }
  },

  onShow() {
    const user = getUserInfo()
    this.setData({
      username: user.username,
      nickname: user.nickname,
      credits: user.credits,
      'belongs.companyName': user.company.companyName,
      phoneNumber: user.phoneNumber
    })
    // 可能需要重新写
    switch(user.roles.length){
      case 3:
        this.setData({
          user,
          userType: '队站管理员'
        })
        break;
      case 2:
        this.setData({
          user,
          userType: '管理员'
        })
        break;
      case 1:
        this.setData({
          user,
          userType: '普通用户'
        })
        break;
    }
     // 设置当前位置信息
     getLocationInfo().then(res=>{
      this.setData({
        province: res.province,
        city: res.city
      })
    }) 
  },

  chooseImage(){
    var that = this
    wx.chooseMedia({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      mediaType: ['image','video'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          imgData:res.tempFiles[0]
        })
      }
    }); 
  },

  async openPop(){
    this.setData({
      isPopShow: true
    })
    const res = await app.call({
      path:'/company/search',
      method: 'POST',
      header: {
          'X-WX-SERVICE': 'fire-assistant-s'
        },
      data:{"province":this.data.province,"cityName":this.data.city}
    })
    this.setData({
      stations: res.content,
      belongs: res.content[0]
    })
  },

  confirmPop(){
    this.setData({
      isPopShow: false,
    })
  },
  improveToAdmin(){
    if(this.data.user.applyAdmin){
      wx.showModal({
        title: '提示',
        content: '该账号正在申请成为管理员，请勿重复提交申请',
      })
    }else{
      wx.showModal({
        content: '您是否申请成为管理员?',
        complete: (res) => {
          if (res.confirm) {
            app.call({
              path:'/wechatUser/elevate',
              method: 'get',
              header: {
                  'X-WX-SERVICE': 'fire-assistant-s'
                },
            }).then(res=>{
              wx.showModal({
                content: '申请发送成功，请您耐心等待',
              })
            })
          }
        }
      })
    }
  },
  
  bindChange(e) {
    this.setData({
      belongs : this.data.stations[e.detail.value[0]]
    })
  },

  updateInfo(){
    if(this.data.imgData.fileType !== 'initial'){
      const file = this.data.user.file
     // 删除数据库中的图像
     if(file){
       // 上传图像 更新图像id
      let filePath = this.data.imgData.tempFilePath
      let name = filePath.substring(filePath.lastIndexOf('/')+1)
       // 在数据库表中上传
      uploadInitFile(app,"user", this.data.imgData, this.data.user.id).then((res)=>{
        if(res.key){
           // 在对象存储中上传
          handleFileUploading(name, filePath, app)
          //绑定 id进行更新
          const data = {
              username : this.data.username,
              phoneNumber : this.data.phoneNumber,
              companyId :this.data.belongs.id ,
              fileId: res.id
          }
          this.updateBasicInfo(data, res).then(resp => {
              // 从数据库删除照片
              deleteFileFromDbs(app, "user", file.id).then(resd =>{
                if(resd.code!==500){
                  // 对象存储中的照片
                  deleteFile(file, app).then(resl=>{
                    // 重新设置user信息
                    wx.switchTab({
                      url: '../homePage/index',
                    })
                  })
                }
              })
          })
        }
      })
     }else{
        // 上传图像 更新图像id
      let filePath = this.data.imgData.tempFilePath
      let name = filePath.substring(filePath.lastIndexOf('/')+1)
       // 在数据库表中上传
      uploadInitFile(app,"user", this.data.imgData, this.data.user.id).then((res)=>{
        if(res.key){
           // 在对象存储中上传
          handleFileUploading(name, filePath, app)
          //绑定 id进行更新
          const data = {
              username : this.data.username,
              phoneNumber : this.data.phoneNumber,
              companyId :this.data.belongs.id ,
              fileId : res.id
          }
          //更新 本地user数据
          this.updateBasicInfo(data, res).then(resp => {
            wx.navigateTo({
              url: '../homePage/index',
            })  
           })
        }
      })
     }
    } else{
      const data = {
        username : this.data.username,
        phoneNumber : this.data.phoneNumber,
        companyId :this.data.belongs.id 
      }
      this.updateBasicInfo(data,"").then(res=>{
        if(res.id){
          wx.switchTab({
            url: '../homePage/index',
          })
        }
      })
    }
  },

  // 更新用户信息 绑定图像
  updateBasicInfo(data, file){
    // 在本地完成更新 用户信息 图像
    const user = getUserInfo()
    user.username = data.username
    user.phoneNumber = data.phoneNumber
    user.companyId = data.companyId
    if(file !== ""){
      user.file = file
    }

    setUserInfo(user)
    return new Promise(resolve=>{
      resolve(
        app.call({
          path:`/users/${this.data.user.id}`,
          method: 'put',
          header: {
              'X-WX-SERVICE': 'fire-assistant-s',
              'tokens': getTokenKey()//必须添加#######
            },
          data:data
        })
      )
    })
  },

  unmInput(e){
    this.setData({
      username: e.detail.value
    })
  },
  telInput(e){
    this.setData({
      phoneNumber: e.detail.value
    })
  },

  closePop(){
    this.setData({
      isPopShow: false
    })
  }
})